package com.funny.wallpaper

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Canvas
import android.graphics.RectF
import android.os.Handler
import android.os.HandlerThread
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import com.airbnb.lottie.LottieComposition
import com.airbnb.lottie.LottieCompositionFactory
import com.airbnb.lottie.LottieDrawable
import com.`fun`.funlivewallpaper.MainActivity2
import com.`fun`.funlivewallpaper.R

class FunnySurfaceView @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = -1,
    defStyleRes: Int = -1
) : SurfaceView(context, attrs, defStyleAttr, defStyleRes), SurfaceHolder.Callback {
    private val tapGestureDetector: GestureDetector
    private var mSurfaceHolder: SurfaceHolder? = null
    private var isVisible = false
    private var myHandlerThread: MyHandlerThread? = null
    private var mLottieDrawable: LottieDrawable? = null
    private var hongbaoTop = 0f
    private var hongbaoBottom = 0f

    // android.view.SurfaceView
    override fun getHolder(): SurfaceHolder {
        val surfaceHolder0 = mSurfaceHolder
        return surfaceHolder0 ?: super.getHolder()
    }

    fun setHolder(surfaceHolder0: SurfaceHolder) {
        mSurfaceHolder = surfaceHolder0
        surfaceHolder0.addCallback(this)
    }

    init {
        tapGestureDetector = GestureDetector(context, object : SimpleOnGestureListener() {
            override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
                val y = e.y
                if (y > hongbaoTop && y < hongbaoBottom) {
                    try {
                        val intent = Intent(getContext(), MainActivity2::class.java)
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        getContext().startActivity(intent)
                    } catch (eee: Exception) {
                        eee.printStackTrace()
                    }
                }
                return super.onSingleTapConfirmed(e)
            }
        })
    }

    fun onVisChanged(z: Boolean) {
        isVisible = z
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        if (myHandlerThread != null) {
            myHandlerThread!!.cancelAnim()
            myHandlerThread!!.quitSafely()
            myHandlerThread = null
        }
        myHandlerThread = MyHandlerThread()
        myHandlerThread!!.start()
        myHandlerThread!!.postRunnable { ilIIL1IiL() }
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}
    override fun surfaceDestroyed(holder: SurfaceHolder) {
        synchronized(this) {
            if (myHandlerThread != null) {
                myHandlerThread!!.quitSafely()
                myHandlerThread = null
            }
            val lottieDrawable0 = mLottieDrawable
            if (lottieDrawable0 != null) {
                lottieDrawable0.removeAllAnimatorListeners()
                mLottieDrawable!!.cancelAnimation()
                mLottieDrawable = null
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")  // android.view.View
    override fun onTouchEvent(motionEvent: MotionEvent): Boolean {
        tapGestureDetector.onTouchEvent(motionEvent)
        return true
    }

    private fun ilIIL1IiL() {
        drawCanvas()
        setAndStartLottie()
    }

    private fun drawCanvas() {
        if (isVisible) {
            val canvas0: Canvas?
            val surfaceHolder0 = mSurfaceHolder
            try {
                canvas0 = surfaceHolder0!!.lockCanvas()
                try {
                    if (canvas0 != null) {
                        if (FunnyWallpaperHelper.hasSetInWallpaper) {
                            drawWallpaper(canvas0)
                        } else {
                            drawPreview(canvas0)
                        }
                    }
                } catch (_: Exception) {
                }
                surfaceHolder0.unlockCanvasAndPost(canvas0)
            } catch (unused_ex: Exception) {
                unused_ex.printStackTrace()
            }
        }
    }

    private fun setAndStartLottie() {
        val lottieDrawable0 = LottieDrawable()
        mLottieDrawable = lottieDrawable0
        lottieDrawable0.enableMergePathsForKitKatAndAbove(true)
        mLottieDrawable!!.setComposition(
            LottieCompositionFactory.fromAssetSync(
                this.context,
                "lottie/live1_finger.lottie"
            ).value as LottieComposition
        )
        //        this.mLottieDrawable.setComposition((LottieComposition) LottieCompositionFactory.fromRawResSync(this.getContext(), R.raw.xiaoshou).getValue());
        mLottieDrawable!!.repeatCount = -1
        mLottieDrawable!!.setBounds(
            0,
            0,
            FunnyWallpaperHelper.getDimensionPixelSize(context, R.dimen.dp_80),
            FunnyWallpaperHelper.getDimensionPixelSize(
                context, R.dimen.dp_80
            )
        )
        mLottieDrawable!!.addAnimatorUpdateListener { drawCanvas() }
        //        this.mLottieDrawable.start();
        mLottieDrawable!!.playAnimation()
    }

    private fun drawPreview(canvas: Canvas) {
        try {
            // draw background
            val bitmap0 = FunnyWallpaperHelper.getWallpaperPreviewBg(context)
            val rectF1 = RectF(
                0.0f,
                0.0f,
                FunnyWallpaperHelper.screenWidth.toFloat(),
                FunnyWallpaperHelper.screenHeight.toFloat()
            )
            canvas.drawBitmap(bitmap0!!, null, rectF1, null)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        try {
            // 绘制小手手
            if (mLottieDrawable != null) {
                canvas.save()
                canvas.translate(
                    FunnyWallpaperHelper.screenWidth - mLottieDrawable!!.getBounds()
                        .width() * 3 / 2f,
                    (FunnyWallpaperHelper.screenHeight - mLottieDrawable!!.getBounds()
                        .height() - FunnyWallpaperHelper.getDimensionPixelSize(
                        context, R.dimen.dp_20
                    )).toFloat()
                )
                mLottieDrawable!!.draw(canvas)
                canvas.restore()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun drawWallpaper(canvas: Canvas) {
        try {
            // background
            val bitmap0 = FunnyWallpaperHelper.getDefaultWallpaperBg(context)
            val rectF1 = RectF(
                0.0f,
                0.0f,
                FunnyWallpaperHelper.screenWidth.toFloat(),
                FunnyWallpaperHelper.screenHeight.toFloat()
            )
            canvas.drawBitmap(bitmap0!!, null, rectF1, null)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        try {
            // 绘制红包按钮
            canvas.save()
            val rectF1 = RectF(
                0.0f,
                0.0f,
                FunnyWallpaperHelper.wallpaperHongBaoWidth.toFloat(),
                FunnyWallpaperHelper.wallpaperHongBaoHeight.toFloat()
            )
            hongbaoTop =
                FunnyWallpaperHelper.screenHeight - rectF1.height() - FunnyWallpaperHelper.getDimensionPixelSize(
                    context, R.dimen.dp_139
                )
            hongbaoBottom = rectF1.height() + hongbaoTop
            canvas.translate(
                FunnyWallpaperHelper.screenWidth / 2f - rectF1.width() / 2f,
                hongbaoTop
            )
            val bitmap0 = FunnyWallpaperHelper.getWallpaperHongbaoBg(context)
            canvas.drawBitmap(bitmap0!!, null, rectF1, null)
            canvas.restore()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        try {
            // 绘制小手手
            if (mLottieDrawable != null) {
                canvas.save()
                canvas.translate(
                    (FunnyWallpaperHelper.screenWidth - mLottieDrawable!!.getBounds()
                        .width()).toFloat(),
                    hongbaoTop - mLottieDrawable!!.getBounds().height() / 2f
                )
                mLottieDrawable!!.draw(canvas)
                canvas.restore()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    class MyHandlerThread : HandlerThread("SurfaceDrawThread") {
        private var mHandler: Handler? = null
        fun cancelAnim() {
            val handler0 = mHandler
            if (handler0 != null) {
                handler0.removeCallbacksAndMessages(null)
                mHandler = null
            }
        }

        fun postRunnable(runnable0: Runnable) {
            if (mHandler == null) {
                mHandler = Handler(this.getLooper())
            }
            mHandler!!.removeCallbacksAndMessages(null)
            mHandler!!.post { startRunnableAndAnim(runnable0) }
        }

        private fun startRunnableAndAnim(runnable0: Runnable) {
            runnable0.run()
        }

        override fun start() {
            synchronized(this) { super.start() }
        }
    }
}
